from django.shortcuts import render
from ..models import Logs
from functools import wraps
from django.http import JsonResponse
import typing as t
# Create your views here.

def record_logs(request,success:bool = True):
    """
    记录日志
    :param request:
    :return:
    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
    else:
        ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
    logs = Logs(
        method=request.method,
        user_id=request.user.id,
        url=request.path,
        desc=request.GET,
        ip = ip,
        success=success,
        user_agent=request.META.get('HTTP_USER_AGENT')
    )
    logs.save()

def view_logs_required(func):
    """
    记录日志装饰器
    :param func:
    :return:
    """
    @wraps(func)
    def wrapper(request,*args,**kwargs):
        record_logs(request)
        return func(request,*args,**kwargs)
    return wrapper


def permission_required(permission:str):
    """
    权限装饰器
    :param permission:
    :return:
    """
    def decorator(func):
        @wraps(func)
        def wrapper(request,*args,**kwargs):
            if permission not in request.session.get('powers'):
                record_logs(request, success=False)
                return render(request, 'view/exception/403.html')
            else:
                power_dict = {power:True for power in request.session.get('powers')}
                request.powers = power_dict
                return func(request, *args, **kwargs)
        return wrapper
    return decorator


def success_api(message:str = '成功',code:int = 200):
    return JsonResponse({'success': True, 'message': message, 'code': code})

def failure_api(message:str = '失败',code:int = 400):
    return JsonResponse({'success': False, 'message': message, 'code': code})

def table_api(success:bool = True,message:str = "",code:int = 0,total:int = 0,result:t.Union[dict,list] = None):
    return JsonResponse({'success': success, 'message': message, 'code': code, 'total': total,'result': result})